package com.eightbears.beboy.base.view.record;

import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.eightbears.beboy.R;
import com.eightbears.beboy.base.BaseActivity;
import com.eightbears.beboy.base.BaseApplication;
import com.yixia.camera.MediaRecorderNative;
import com.yixia.camera.VCamera;
import com.yixia.camera.model.MediaObject;
import com.yixia.videoeditor.adapter.UtilityAdapter;

import java.util.LinkedList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class RecorderActivity extends BaseActivity {

    private static final int REQUEST_KEY = 100;
    private static final int HANDLER_RECORD = 200;
    private static final int HANDLER_EDIT_VIDEO = 201;


    @BindView(R.id.rb_start)
    RecordedButton rb_start;
    @BindView(R.id.sv_surface)
    FocusSurfaceView sv_surface;
    @BindView(R.id.iv_finish)
    ImageView iv_finish;
    @BindView(R.id.iv_back)
    ImageView iv_back;

    @BindView(R.id.rl_bottom)
    RelativeLayout rl_bottom;
    @BindView(R.id.rl_bottom2)
    RelativeLayout rl_bottom2;
    @BindView(R.id.vv_play)
    MyVideoView vv_play;
    @BindView(R.id.iv_close)
    ImageView iv_close;
    @BindView(R.id.view_loading)
    View view_loading;
    @BindView(R.id.tv_loading_text)
    TextView tv_loading_text;
    @BindView(R.id.iv_close_activity)
    ImageView iv_close_activity;
    @BindView(R.id.iv_switch)
    ImageView iv_switch;

    private MediaRecorderNative mMediaRecorder;
    private MediaObject mMediaObject;

    //本次段落是否录制完成
    private boolean isRecordedOver;
    private String videoPath;
    private int duration;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_recorder);

        initView();
        initData();
        initEvent();
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        initMediaRecorder();

    }

    @Override
    protected void initData() {
        int maxDuration = 10000;
        rb_start.setMax(maxDuration);
    }

    @Override
    protected void initEvent() {
        rb_start.setOnGestureListener(new RecordedButton.OnGestureListener() {
            @Override
            public void onLongClick() {
                isRecordedOver = false;
                mMediaRecorder.startRecord();
                rb_start.setSplit();
                myHandler.sendEmptyMessageDelayed(HANDLER_RECORD, 100);
            }

            @Override
            public void onClick() {

            }

            @Override
            public void onLift() {
                isRecordedOver = true;
                mMediaRecorder.stopRecord();
                videoFinish();
            }

            @Override
            public void onOver() {
                isRecordedOver = true;
                rb_start.closeButton();
                mMediaRecorder.stopRecord();
                videoFinish();
            }
        });
    }


    /**
     * 初始化录制对象
     */
    private void initMediaRecorder() {

        mMediaRecorder = new MediaRecorderNative();
        String key = String.valueOf(System.currentTimeMillis());
        //设置缓存文件夹
        mMediaObject = mMediaRecorder.setOutputDirectory(key, VCamera.getVideoCachePath());
        //设置视频预览源
        mMediaRecorder.setSurfaceHolder(sv_surface.getHolder());
        //准备
        mMediaRecorder.prepare();
        //滤波器相关
        UtilityAdapter.freeFilterParser();
        UtilityAdapter.initFilterParser();
    }

    private void changeButton(boolean flag){

        if(flag){
            rl_bottom.setVisibility(View.VISIBLE);
        }else{
            rl_bottom.setVisibility(View.GONE);
        }
    }

    private void videoFinish() {
        changeButton(false);
        rb_start.setVisibility(View.GONE);
        iv_close_activity.setVisibility(View.GONE);
        iv_switch.setVisibility(View.GONE);
        myHandler.sendEmptyMessage(HANDLER_EDIT_VIDEO);
    }

    /**
     * 合成视频
     */
    @RequiresApi(api = Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    private void syntVideo(){

        //ffmpeg -i "concat:ts0.ts|ts1.ts|ts2.ts|ts3.ts" -c copy -bsf:a aac_adtstoasc out2.mp4
        StringBuilder sb = new StringBuilder("ffmpeg");
        sb.append(" -i");
        String concat="concat:";
        for (MediaObject.MediaPart part : mMediaObject.getMediaParts()){
            concat+=part.mediaPath;
            concat += "|";
        }
        concat = concat.substring(0, concat.length()-1);
        sb.append(" "+concat);
        sb.append(" -c");
        sb.append(" copy");
        sb.append(" -bsf:a");
        sb.append(" aac_adtstoasc");
        sb.append(" -y");
        String output = BaseApplication.VIDEO_PATH +"/temp.mp4";
        sb.append(" "+output);
        int i = UtilityAdapter.FFmpegRun("", sb.toString());
        duration = mMediaObject.getDuration();
        if(i == 0){
            if(mMediaRecorder.isFrontCamera()){
                // ffmpeg -i 待旋转的视频文件.mp4 -c copy -metadata:s:v:0 rotate=90 旋转后的视频文件.mp4
                String input = BaseApplication.VIDEO_PATH +"/temp.mp4";
                String videoOutput = BaseApplication.VIDEO_PATH +"/success.mp4";
                StringBuilder s = new StringBuilder("ffmpeg");
                s.append(" -i");
                s.append(" " + input);
                s.append(" -c copy");
                s.append(" -metadata:s:v:0");
                s.append(" rotate=180");
                s.append(" " + videoOutput);
                int result = UtilityAdapter.FFmpegRun("", s.toString());
                if(result == 0){
                    playVideo(videoOutput);
                }
                videoPath = videoOutput;

                return;
            }
            videoPath = output;
            playVideo(output);

        }else{
            Toast.makeText(getApplicationContext(), "视频合成失败", Toast.LENGTH_SHORT).show();
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    private void playVideo(String output) {
        rl_bottom2.setVisibility(View.VISIBLE);
        vv_play.setVisibility(View.VISIBLE);

        vv_play.setVideoPath(output);
        vv_play.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {

                vv_play.setLooping(true);
                vv_play.start();
            }
        });
        if(vv_play.isPrepared()){
            vv_play.setLooping(true);
            vv_play.start();
        }
    }

    private Handler myHandler = new Handler(){
        @RequiresApi(api = Build.VERSION_CODES.ICE_CREAM_SANDWICH)
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case HANDLER_RECORD://拍摄视频的handler
                    if(!isRecordedOver){
                        if(rl_bottom.getVisibility() == View.VISIBLE) {
                            changeButton(false);
                        }
                        rb_start.setProgress(mMediaObject.getDuration());
                        myHandler.sendEmptyMessageDelayed(HANDLER_RECORD, 30);
                    }
                    break;
                case HANDLER_EDIT_VIDEO://合成视频的handler
                    int progress = UtilityAdapter.FilterParserAction("", UtilityAdapter.PARSERACTION_PROGRESS);
                    view_loading.setVisibility(View.VISIBLE);
                    tv_loading_text.setText("视频编译中 "+progress+"%");
                    if (progress == 100) {
                        syntVideo();
                        view_loading.setVisibility(View.GONE);
                    } else if (progress == -1) {
                        view_loading.setVisibility(View.GONE);
                        Toast.makeText(getApplicationContext(), "视频合成失败", Toast.LENGTH_SHORT).show();
                    } else {
                        sendEmptyMessageDelayed(HANDLER_EDIT_VIDEO, 30);
                    }
                    break;
            }
        }
    };

    /**
     * 初始化视频拍摄状态
     */
    @RequiresApi(api = Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    private void initMediaRecorderState(){
        vv_play.setVisibility(View.GONE);
        vv_play.pause();

        rb_start.setVisibility(View.VISIBLE);
        iv_close_activity.setVisibility(View.VISIBLE);
        iv_switch.setVisibility(View.VISIBLE);
        rl_bottom2.setVisibility(View.GONE);
        changeButton(false);
        view_loading.setVisibility(View.GONE);
        LinkedList<MediaObject.MediaPart> list = new LinkedList<>();
        list.addAll(mMediaObject.getMediaParts());

        for (MediaObject.MediaPart part : list){
            mMediaObject.removePart(part, true);
        }

        rb_start.setProgress(mMediaObject.getDuration());
        rb_start.cleanSplit();
    }

    @RequiresApi(api = Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    @OnClick(R.id.iv_close) void back(){
        initMediaRecorderState();
    }


    @OnClick(R.id.iv_next) void submitVideo(){
        Intent intent = getIntent().putExtra("path", videoPath).putExtra("dur", duration);
        setResult(Activity.RESULT_OK, intent);
        finish();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mMediaRecorder.startPreview();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMediaRecorder.stopPreview();
        initMediaRecorderState();
    }

    @OnClick(R.id.iv_close_activity) void finishActivity(){
        finish();
    }

    @OnClick(R.id.iv_switch) void switchCamera(){
        mMediaRecorder.switchCamera();
    }

    @Override
    public void onBackPressed() {
        if(rb_start.getSplitCount() == 0) {
            super.onBackPressed();
        }else{
            initMediaRecorderState();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMediaObject.cleanTheme();
        mMediaRecorder.release();
    }
}
